package rsj.service.account;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import common.entity.PageInfo;
import common.statusenum.RoleEnum;
import common.statusenum.UserTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import rsj.api.account.entity.*;
import rsj.api.user.entity.UserAccount;
import rsj.manager.OrgProManager;
import rsj.service.auth.IAuthService;
import rsj.service.contract.IContractService;
import rsj.service.organization.IOrganizationService;
import rsj.service.user.IUserService;
import rsj.sql.account.AccountDao;

import java.util.List;

/**
 * 账号
 *
 * @author yuanqinglong
 * @since 2021/7/14 13:40
 */
@Service
public class AccountServiceImpl implements IAccountService {

    /**
     * 账户
     */
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private OrgProManager orgProManager;
    /**
     * 账号标识
     */
    @Autowired
    private IAuthService authServiceImpl;
    /**
     * 用户
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 合同
     */
    @Autowired
    private IContractService contractServiceImpl;
    /**
     * 机构
     */
    @Autowired
    private IOrganizationService organizationServiceImpl;
    /**
     * 权限
     */
    @Autowired
    private IAccountProductService accountProductServiceImpl;


    /**
     * 账户列表
     *
     * @param accountQueryParam 账户查询参数
     * @return {@link List<AccountTable>}
     */
    @Override
    public List<AccountTable> accountList(AccountQueryParam accountQueryParam) {
        PageInfo pageInfo = accountQueryParam.getPageInfo();
        TableNode tableNode = accountDao.accountList(accountQueryParam.getCustSname(), accountQueryParam.getCustId(),
                accountQueryParam.getAutKeyid(), pageInfo.getPageSize(), pageInfo.getPageOffSet());
        return JSON.parseArray(tableNode.toJson(), AccountTable.class);
    }


    /**
     * 账户数
     *
     * @param accountQueryParam 账户查询参数
     * @return int
     */
    @Override
    public int accountCount(AccountQueryParam accountQueryParam) {
        Node accountTotal = accountDao.accountCount(accountQueryParam.getCustSname(), accountQueryParam.getCustId(), accountQueryParam.getAutKeyid());
        return accountTotal.valueInt();
    }


    /**
     * 添加账户
     *
     * @param createAccount 账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAccount(AccountInformation createAccount) {
        UserAccount createUser = createAccount.getUserAccount();
        IAccountService.verifyAccount(createUser.getUserUname());
        // 创建机构
        Organization createOrganization = createAccount.getOrganization();
        createOrganization.setOrgUserName(createUser.getUserUname());
        Organization organization = organizationServiceImpl.addOrganization(createOrganization);

        // 保存权限
        List<AccountProduct> accountProducts = createAccount.getAccountProducts();
        if (!CollectionUtils.isEmpty(accountProducts)) {
            accountProductServiceImpl.addAccountProduct(accountProducts, organization.getOrgId());
        }

        // 2021/7/16 创建账户唯一标识
        orgProManager.createAuthAutoCloseConnection(organization.getOrgId());

        // 创建用户
        createUser.setUserOrgId(organization.getOrgId());
        createUser.setUserRoleId(RoleEnum.CUSTOMER.getCode());
        createUser.setUserType(UserTypeEnum.ORGANIZATION.getCode());
        createUser.setUserName(createUser.getUserUname());
        userServiceImpl.addUser(createUser);

    }


    /**
     * 更新帐户
     *
     * @param createAccount 创建账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAccount(AccountInformation createAccount) {
        // 更新账号
        userServiceImpl.updateUserPassword(createAccount.getUserAccount());

        // 更新权限
        List<AccountProduct> accountProducts = createAccount.getAccountProducts();
        if (!CollectionUtils.isEmpty(accountProducts)) {
            accountProductServiceImpl.addAccountProduct(accountProducts,createAccount.getOrganization().getOrgId());
        }

        // 更新机构
        Organization organization = createAccount.getOrganization();
        organizationServiceImpl.updateOrganization(organization);
    }


    /**
     * 获得账户
     *
     * @param orgId 机构id
     * @return {@link AccountInformation}
     */
    @Override
    public AccountInformation getAccount(String orgId) {
        // 机构信息
        Organization organization = organizationServiceImpl.getOrganization(orgId);
        String keyIdByOrganization = authServiceImpl.getKeyIdByOrganization(orgId);
        organization.setAutKeyid(keyIdByOrganization);
        // 权限信息
        List<AccountProduct> accountProducts = accountProductServiceImpl.getAccountProducts(orgId);
        // 用户信息
        UserAccount userAccount = userServiceImpl.getUserAccount(orgId);
        return new AccountInformation(organization, userAccount, accountProducts);
    }


    /**
     * 更新帐户状态
     *
     * @param accountStatus 帐户状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAccountStatus(AccountStatus accountStatus) {
        // 更新用户状态
        accountDao.updateAccountStatus(accountStatus);
        // 更新合同状态
        List<String> contractIds = contractServiceImpl.contractUnderOrganization(accountStatus.getOrgId());
        if (!CollectionUtils.isEmpty(contractIds)) {
            for (String contractId : contractIds) {
                contractServiceImpl.updateContractStatus(contractId, accountStatus.getStatus());
            }
        }
    }


}
